package cn.edu.njuit.children.apis;

import cn.edu.njuit.children.common.Result;
import cn.edu.njuit.children.entity.UserAccount;
import cn.edu.njuit.children.service.TokenService;
import cn.edu.njuit.children.service.UserService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.edu.njuit.children.common.ResultCode.*;

/**
 * @Description: TODO
 * @Data: 2022/11/29 8:40
 * @Author: guzy
 */
@RestController
@RequestMapping("/api")
@Api(value = "登录注册", tags = "登录注册")
public class LoginApi {


    @Autowired
    AuthenticationManagerBuilder authenticationManagerBuilder;

    @Autowired
    UserService userService;

    @Autowired
    TokenService tokenService;

    @ApiOperation("账户登录")
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "手机号", required = true), @ApiImplicitParam(name = "password", value = "登录密码", required = true)})
    @PostMapping("/login")
    public Result doLogin(@RequestParam(required = true) String phone, @RequestParam(required = true) String password) {

        User loginUser = null;
        try {
            //使用SpringSecurity框架进行登录
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(phone, password);

            //使用springSecurity进行登录认真
            Authentication authenticate = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
            loginUser = (User) authenticate.getPrincipal();
        } catch (Exception e) {
            return Result.failure(USER_ACCOUNT_OR_PASSWORD_ERROR, "null");
        }
        try {
//            String token = this.accountService.doLogin(login, password);
            String token = tokenService.getToken(loginUser.getUsername());
            JSONObject result = new JSONObject();
            result.put("id_token", token);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject error = new JSONObject();
            error.put("errorInfo", e.getMessage());
            return Result.failure(USER_SIGN_IN_FAIL, error);
        }
    }


    @ApiOperation("注册新账户")
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "手机号", required = true),
            @ApiImplicitParam(name = "password", value = "登录密码", required = true),
            @ApiImplicitParam(name = "defaultRole", value = "默认角色名", required = false)})
    @PostMapping("/regist")
    public Result registerAccount(@RequestParam(required = true) String phone,
                                  @RequestParam(required = true) String password,
                                  @RequestParam(required = false, defaultValue = "role_user") String defaultRole) {
        try {
            UserAccount user = userService.regAccount(phone, password, defaultRole);
            return Result.success(user);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject error = new JSONObject();
            error.put("errorInfo", e.getMessage());
            return Result.failure(USER_SIGN_UP_FAIL, error);
        }
    }

}
